/**
 * @description 任务-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const process = require('child_process')
const ox = require('@daelui/oxjs')
const Service = require('./service.js')
const { messager } = require('@daelui/oxkit')

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 服务
    this.$service = new Service(args)
    // 初始化计时器
    this.initTimer()
  }

  /**
   * @function 计时任务查询
  */
  initTimer () {
    // 每10分种查询一次数据
    this.queryTimer = setInterval(() => {
      clearInterval(this.checkTimer)
      let defer = this.$service.queryAll({
        fields: [],
        params: {
          status: 1
        },
        excute: {
          operators: [
            {field: 'status', operator: 'EQUAL'}
          ],
          sort: [
            {field: 'createTime', by: 'desc'},
            {field: 'order', by: 'desc'}
          ]
        }
      })
      defer.then(res => {
        // 每10秒
        this.checkTimer = setInterval(() => {
          let data = res.data
          data.forEach(item => {
            try {
              item.trigger = JSON.parse(item.trigger)
              item.operation = JSON.parse(item.operation)
            } catch (e) {
              item.trigger = {}
              item.operation = {}
            }
            // 触发任务
            this.triggerTask(item)
          })
        }, 15000)
      })
    }, 10 * 60 * 1000)
  }

  /**
   * @function 触发计时任务
  */
  triggerTask (task) {
    let trigger = task.trigger
    // 当前时间
    let cur = new Date()
    // 以日为单位定时任务
    if (String(trigger.type) === '1') {
      let date = new Date(trigger.timePoint)
      let hour = date.getHours()
      let minute = date.getMinutes()
      let second = date.getSeconds()
      let pointSeconds = hour * 60 * 60 + minute * 60 + second
      // 周期数
      let cycleTime = parseInt(trigger.cycleTime)
      if (isNaN(cycleTime) || cycleTime < 1) {
        return false
      }
      // 周期单位
      let unit = trigger.unit
      if (!/^(year|month|week|day|hour|minute|second)$/.test(unit)) {
        return false
      }
      // 一个周期的秒数
      let unitSeconds = 0
      switch(unit) {
        case 'year':
          unitSeconds = 365 * 24 * 60 * 60 * cycleTime
          break
        case 'month':
          unitSeconds = 30 * 24 * 60 * 60 * cycleTime
          break
        case 'week':
          unitSeconds = 7 * 24 * 60 * 60 * cycleTime
          break
        case 'day':
          unitSeconds += 24 * 60 * 60 * cycleTime
          break
        case 'hour':
          unitSeconds = 60 * 60 * cycleTime
          break
        case 'minute':
          unitSeconds = 60 * cycleTime
          break
        case 'second':
          unitSeconds = cycleTime
          break
      }
      // 当前时间点
      let curHour = cur.getHours()
      let curMinute = cur.getMinutes()
      let curSecond = cur.getSeconds()
      let curSeconds = curHour * 60 * 60 + curMinute * 60 + curSecond
      // 当前可执行的次数
      let times = Math.floor(cur.getTime() / 1000 / unitSeconds)
      // 执行日志
      let count = parseInt(task.count) ? parseInt(task.count) : 0
      // console.log(times, count, curSeconds, pointSeconds)
      if (times > count && curSeconds >= pointSeconds) {
        task.count = times
        this.$service.update({
          params: {
            id: task.id,
            count: task.count,
            runDate: cur.getTime()
          }
        })
        // 执行操作
        this.runOperation(task)
      }
    }
  }

  /**
   * @function 执行任务操作
  */
  runOperation (task) {
    let type = String(task.operation.type)
    // 打开窗口
    if (type === '1') {
      messager.msg(task.operation.content, task.operation.title || '消息')
    }
    // 执行定义命令
    else if (type === '2') {
      var cmd = 'ifconfig'
      process.exec(cmd, function(error, stdout, stderr) {
        console.log('error:' + error)
        console.log('stdout:' + stdout)
        console.log('stderr:' + stderr)
      })
    }
  }
}

// 前置加载
Controller.isPreInit = true

module.exports = Controller